import { defineStore } from 'pinia'
import { store } from '../index'
import { parse, stringify } from 'zipson'

interface UserInfo {
  name: string
  email: string
  avatar: string
}

interface UserState {
  userInfo: UserInfo
}

export const useUserStore = defineStore('userStore', {
  state: (): UserState => ({
    userInfo: {
      name: '',
      email: '',
      avatar: ''
    }
  }),
  getters: {
    isLoggedIn: (state) => state.userInfo.name !== ''
  },
  actions: {
    login(userInfo: UserInfo) {
      this.userInfo = userInfo
    },
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
    },
    logout() {
      this.userInfo = {
        name: '',
        email: '',
        avatar: ''
      }
    }
  },
  persist: {
    key: 'user',
    storage: localStorage,
    serializer: {
      deserialize: parse,
      serialize: stringify
    }
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
